package com.hulman.oms.service;

import com.github.benmanes.caffeine.cache.Cache;
import com.hulman.oms.bean.Msg;
import com.hulman.oms.dao.MiniProgramDao;
import com.hulman.oms.util.DateUtil;
import com.hulman.oms.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 企业微信小程序服务
 */
@Service
@Slf4j
public class MiniProgramService
{
    public static final String MINI_PROGRAM_TOKEN = "mini-program-token";
    @Autowired
    private MiniProgramDao miniProgramDao;
    @Autowired
    private UserService userService;
    @Autowired
    private Cache<String, String> tokenCache;

    public String getAccessToken()
    {
        String token = tokenCache.getIfPresent(MINI_PROGRAM_TOKEN);
        if (!StringUtil.isEmpty(token))
        {
            return token;
        } else
        {
            token = miniProgramDao.getAccessToken();
            tokenCache.put(MINI_PROGRAM_TOKEN, token);
            return token;
        }
    }

    public String code2Session(String code)
    {
        String accessToken = getAccessToken();
        return miniProgramDao.code2Session(accessToken, code);
    }

    @Async
    public void sendMsgAsync(Msg msg)
    {
        sendMsg(msg);
    }

    /**
     * 发送通知
     *
     * @param
     */
    public void sendMsg(Msg msg)
    {
        if (!miniProgramDao.isMiniProgramEnabled())
        {
            log.info("企业微信消息未启用");
            return;
        }
        String ownerId = userService.convertToAccount(msg.getOwnerId());
        String accessToken = getAccessToken();
        String title = msg.getTitle();
        String description = DateUtil.toDateTime(msg.getCreateTime());
        Map<String, String> items = new LinkedHashMap<>();
        msg.itemList().stream().forEach(item ->
        {
            items.put(item.getName(), item.getValue());
        });
        String page = msg.getPath();
        try
        {
            miniProgramDao.sendMiniprogram(accessToken, ownerId, title, description, page, items);
        } catch (Exception ex)
        {
            log.info("sendMsg Error:", ex);
        }
    }

}
